var driver = require('../dao/db');
var async = require('async');
var fs = require('fs');
var utils = require('../dao/utils');

var insertDB = function (data, _default) {

    var url = "mongodb://localhost:27017/manhua";
    var table = "manhua";


    var _query = { "title": data['title'] };

    data['spiderTime'] = new Date();

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, url);
        },
        // 查找
        function (db, callback) {
            driver.find(db, callback, table, _query);
        },
        // 
        function (db, res, callback) {
            // 未找到记录
            if (res.success && res.data.length == 0) {
                driver.insert(db, callback, table, data);
            } else {
                // file(data);
                // 已存在数据库
                if (res.data.length > 0) {
                    var source = res.data[0];

                    // 该漫画已完结
                    if (source['isFinish'] == true) {
                        callback(null, db, res);
                        return;
                    }

                    // 该漫画有更新(同时有多本同名漫画，比较章节数选多的漫画)
                    if (source['chapters'].length < data['chapters'].length) {

                        console.log('update a newly one ' + data['title'] + data['href']);
                        driver.update(db, callback, table, _query, { $set: data });
                        return;
                    }

                    // manhua
                    if (source['href'] == data['href']) {
                        driver.update(db, callback, table, _query, { $set: { "isUpdate": false, "spiderTime": data['spiderTime'] } });
                        return;
                    }

                    callback({ success: false, msg: 'has new one exsit in database' }, db, res);
                    return;
                } else {

                    callback({ success: false, msg: 'error s' }, db, res);
                }

            }
        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }
    ],
        // result
        function (err, result) {
            // console.log("resulte");

            if (err) {
                console.log(err);
                return;
            }

            // console.log('find a new one '+data['title']+data['href']);

            // _default.successHandel(_default);
        }
    );
};

module.exports = insertDB;


var file = function (data) {
    var filename = __dirname + "/repeat.json";
    // 序列化
    var destString = JSON.stringify(data);

    fs.appendFile(filename, destString, 'utf8', (err) => {
        if (err) throw err;
        console.log('The "data to append" was appended to file!');
    });
}